package run;

import hypermedia.video.Blob;
import hypermedia.video.OpenCV;
import processing.core.PApplet;
import processing.core.PConstants;
import processing.core.PImage;
import processing.core.PVector;
import processing.video.Capture;


public class MarioGame extends PApplet {
	
	
	Mario mario;

	boolean capture_mode = true;
	private boolean show_thresh = false;
	MarioGameEnv e;
	MarioGameEnv tmpEnv;
	private OpenCV opencv;

	  public void setup() {
		    size(1000, 650, PConstants.P2D);
		    noStroke();
		    smooth();
		    background(255);
			frameRate(30);
			
			opencv = new OpenCV(this);
			
			if (capture_mode) {
				opencv.capture(1000, 650);
				opencv.read();
			}
			else {
				opencv.loadImage("img.jpg");
			}


			MarioGameEnv e = new MarioGameEnv(opencv,
					  this);
			mario = new Mario(new PVector(300,200),
					e, this);	
			
			final MarioGame game = this;
			Runnable analysis_loop = new Runnable() {
				public void run() {
					while (true) {

						if (capture_mode)
							opencv.read();
						else {
							PImage img = loadImage("img.jpg");
							opencv.copy(img);
						}

						// gameEnv should be given only the Blobs...
						tmpEnv = new MarioGameEnv(opencv, game);
					}
				}
			};
			(new Thread(analysis_loop)).start();

	  }

	  public void draw() {
		// analysis -- done once in a while (do better w/ threading)
		// recomputing the frame takes a long time.
	    background(0);

		  
		if (tmpEnv != null)
			e = tmpEnv;

		

		if (e != null) {
			mario.updateEnv(e);
			// if a new analysis is ready, update it for mario
			if (show_thresh) {
				image(e.cvs.getThresholdedImage(), 0, 0);
			}
			else {
				image(e.cvs.getUnthresholdedImage(), 0, 0);
			}
			e.renderBlobs(this);

			mario.draw(this);
		}
	  }
	  
	  public void keyPressed() {
		  if (key == 'd') {
			  System.out.println("right");
			  mario.right(true);
		  }
		  if (key == 'a') {
			  System.out.println("left");
			  mario.left(true);
		  }
		  if (key =='w') {
			  System.out.println("jump");
			  mario.jump();
		  }
		  if (key == 'x') {
			  System.out.println("reset");
			  mario.reset();
		  }
		  
		  
		  if (key == 'k') {
			  CVSuperImposition.contrast_lev++;

			  System.out.println("brightlevel " + CVSuperImposition.contrast_lev);
		  }
		  if (key == 'm')
			  CVSuperImposition.contrast_lev--;
		  
		  if (key=='p') {
			  CVSuperImposition.bright_lev++;
			  System.out.println("brightlevle " + CVSuperImposition.bright_lev);
		  }
		  if (key == 'l')
			  CVSuperImposition.bright_lev --;
		  
		  if (key == 'z') {
			  show_thresh = ! show_thresh;
		  }
	  }

	  public void keyReleased() {
		  if (key == 'd') {
			  System.out.println("right");
			  mario.right(false);
		  }
		  if (key == 'a') {
			  System.out.println("left");

			  mario.left(false);
		  }
	  }

	  public void mousePressed() {
//		if (capture_mode)
//		  save("img.jpg");
	  }
	  
}
